import { MyNoteService } from '@services/myNote.service';
import { CacheService } from '@services/cache.service';
import { DataService } from '@services/data.service';
import { LoadingService } from '@services/loading.service';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { NavController, ModalController, Platform } from '@ionic/angular';
import { PromptAlarmModal } from '@components/prompt-alarm/prompt-alarm';
import Option from './iotChartOption';
import { Router } from '@angular/router';
import { forkJoin } from 'rxjs';

@Component({
  selector: 'app-iot-operation',
  templateUrl: './iot-operation.html',
  styleUrls: ['./iot-operation.scss'],
})
export class IotOperation implements OnInit, OnDestroy {

  /**
   * @param load 加载动画
   * @param projectId 项目ID
   * @param currentId 集团ID
   * @param createUserId 用户ID
   * @param createUserName 用户Name
   * @param state 切换状态（0：数据栈/1：传感器）
   * @param ionTabbar 底部导航栏
   * @param functionList 生成tab传入数组
   * @param option echarts图表配置
   * @param load 加载动画
   * @param listData 列表数据
   * @param chartData 图表数据
   * @param listType 列表各数据状态
   * @param alarmType 告警状态
   * @param alarmLevel 告警等级
   * @param stackAlarmReason 数据栈告警原因
   * @param transducerAlarmReason 传感器告警原因
   * @param handleType 处理状态
   * @param allNum 告警总数
   * @param page 页面标记（1：集团/2：项目）
   */
  public load: any;
  public projectId: string;
  public currentId: string;
  public createUserId: number;
  public createUserName: string;
  public state: number;
  public ionTabbar: HTMLElement = document.getElementsByTagName('ion-tab-bar')[0];
  public functionList: Array<any> = [];
  public option: any = Option;
  public listData: any = [];
  public chartData: any;
  public listType: any = { 1: '未处理', 2: '未恢复', 3: '已恢复' };
  public stackAlarmType: any = {
    1: '掉线',
    2: '网络不稳定',
    3: '数据栈资源不足'
  };
  public transducerAlarmType: any = {
    1: '掉线',
    2: '电池电量异常',
    3: '数据异常'
  };
  public alarmLevel: any = {
    1: '一般',
    2: '重要',
    3: '紧急'
  };
  public stackAlarmReason: any = {
    1: '断电',
    2: '断网',
    3: '硬件故障',
    4: '丢包率过高',
    5: '网络延时过大',
    6: 'CPU使用率过大',
    7: '内存使用过高',
  };
  public transducerAlarmReason: any = {
    1: '断电',
    2: '断网',
    3: '硬件故障',
    4: '电池电量低',
    5: '电量衰减过快',
    6: '超出上下限',
    7: '数据突变',
  };
  public handleType: any = ['', '已确认', '已到场', '已处理', '已完成'];
  public allNum: number;
  public page: number;
  public untreatedArr: Array<any> = [];
  public doingArr: any = [];
  public recoveryArr: any = [];
  // public projectName;
  constructor(
    public dataservice: DataService,
    public cacheservice: CacheService,
    public loadingService: LoadingService,
    public navCtrl: NavController,
    public modalCtrl: ModalController,
    public router: Router,
    public note: MyNoteService,
    public platform: Platform
  ) {

    const queryParams = this.router.getCurrentNavigation().extras.queryParams;
    this.page = queryParams.page;
  }

  ngOnInit(): void {

    this.platform.backButton.subscribe(res => {
      this.loadClose();
    })

    // 隐藏底部导航
    this.ionTabbar.classList.add('transparent');

    this.projectId = this.cacheservice.currentProject.projectId;
    this.currentId = this.cacheservice.currentCompany.companyId;
    this.createUserId = this.cacheservice.userinfo.userId;
    this.createUserName = this.cacheservice.userinfo.userName;
    // 初始化当前tab页
    this.state = 0;
    this.functionList = [{ functionCode: 0, functionName: '数据栈' }, { functionCode: 1, functionName: '传感器' }];
    // 获取告警列表数据

    this.getList(this.state);
  }

  ngOnDestroy(): void {
    // 显示底部导航
    this.ionTabbar.classList.remove('transparent');
  }

  // 加载动画
  loadClose() {
    if (this.load) {
      this.load.then((res) => {
        res.dismiss();
        this.load = null;
      })
    }
  }

  /**
   * 获取告警列表数据及数据处理
   * @param type 当前状态（0：数据栈/1：传感器）
   * @param parame 传参
   */
  getList(type) {
    const paramsId = this.page === 1 ? this.currentId : this.projectId
    const apiType = this.page === 1 ? 2 : 3;
    const parame = { id: paramsId, apiType: apiType, isAppUse: true };
    const historyParame = { id: paramsId, apiType: apiType, startTime: this.getParmeTime(true), endTime: this.getParmeTime(false) }
    // noDoNum 未处理；doingNum 处理中；recoveryNum 已处理
    this.untreatedArr = [], this.doingArr = [], this.recoveryArr = [];
    this.resetData();
    if (!type) {
      this.dataservice.getIotOperationList(type, parame).subscribe((res: any) => {
        this.loadClose();
        if (res.success) {
          res.data.data.forEach((item) => {
            this.treatUnifyData(this.treatStackData(item));
          });
          this.treatShowData();
        } else {
          this.note.MyNotice('数据出错');
        }
      })
    } else {
      const realMeterData = this.dataservice.getIotOperationList(type, parame);
      const historyMeterData = this.dataservice.getSensorHisAlramList(historyParame);
      forkJoin([realMeterData, historyMeterData]).subscribe((res: any) => {
        this.loadClose();
        if (res.length > 0 && res[0].success && res[1].success) {
          const meterData = [...res[0].data.data, ...res[1].data.data];
          meterData.forEach((item) => {
            this.treatUnifyData(this.treatMeterData(item));
          });
          this.treatShowData();
        } else {
          this.note.MyNotice('数据出错');
        }
      })
    }

  }

  getParmeTime(type) {
    const date = new Date();
    type ? date.setTime(date.getTime()) : date.setTime(date.getTime() - 24 * 60 * 60 * 1000 * 3);
    let month: any = date.getMonth() + 1;
    let day: any = date.getDate();
    if (month < 10) { month = '0' + month }
    if (day < 10) { day = '0' + day }
    return date.getFullYear() + '-' + month + '-' + day;
  }

  // 处理展示数据
  treatShowData() {
    // 数据总条数
    this.allNum = this.untreatedArr.length + this.doingArr.length + this.recoveryArr.length;

    // 图表展示数据
    this.chartData = [{
      value: this.untreatedArr.length,
      name: '未处理',
      status: 1
    },
    {
      value: this.doingArr.length,
      name: '处理中',
      status: 2
    },
    {
      value: this.recoveryArr.length,
      name: '已恢复',
      status: 3
    }];
    const newOption = JSON.parse(JSON.stringify(this.option));
    this.option = newOption;
    // 列表排序
    this.listData = [...this.sortTimeArr(this.untreatedArr), ...this.sortTimeArr(this.doingArr), ...this.sortTimeArr(this.recoveryArr)];
    this.option.series[0].data = this.chartData;
    this.option.color = this.allNum === 0 ? ['#d1d1d1', '#d1d1d1', '#d1d1d1'] : ['#F15755', '#4EA6F0', '#62C97E']
  }

  resetData() {
    this.allNum = 0;
    // 图表展示数据
    this.chartData = [{
      value: 0,
      name: '未处理',
      status: 1
    },
    {
      value: 0,
      name: '处理中',
      status: 2
    },
    {
      value: 0,
      name: '已恢复',
      status: 3
    }];
    this.listData = [];
    const newOption = JSON.parse(JSON.stringify(this.option));
    this.option = newOption;
    this.option.series[0].data = this.chartData;
    this.option.color = ['#d1d1d1', '#d1d1d1', '#d1d1d1']
  }

  // 处理数据栈数据
  treatStackData(item) {
    item.address = item.address || '';
    item.name = this.page === 1 ? item.projectName : item.address;
    item.id = '(' + item.stackId + ')';
    item.alarmTypeName = this.stackAlarmType[item.alarmType];
    item.alarmReason = this.stackAlarmReason[item.reason];
    return item;
  }

  // 处理传感器数据
  treatMeterData(item) {
    item.address = item.address || '';
    let name: string = this.page === 1 ? item.projectName : item.address;
    let id: string;
    let stackIdArr = [];
    let meterIdArr = [];
    item.meters.forEach((c, i, s) => {
      if (i === s.length - 1) {
        name += c.meterName;
      } else {
        name += c.meterName + ',';
      }
      stackIdArr = [...stackIdArr, c.stackId];
      meterIdArr = [...meterIdArr, c.meterId];
    })
    id = `(${Array.from(new Set(stackIdArr)).join(',')}/${meterIdArr.join(',')})`
    item.name = name;
    item.id = id;
    item.alarmTypeName = this.transducerAlarmType[item.alarmType];
    item.alarmReason = item.alarmType === 2 ? this.transducerAlarmReason[item.reason] + '(' + item.quantityElectricity + item.remainDays + ')' : this.transducerAlarmReason[item.reason];
    return item;
  }

  // 处理数据栈和传感器一致数据
  treatUnifyData(item) {
    item.projectId = this.projectId;
    item.createUserId = this.createUserId;
    item.createUserName = this.createUserName;
    item.listType = this.listType[item.status];
    item.handleType = this.handleType[item.procState];
    item.restoreTime = item.recoveryTime;
    if (item.status === 1) {
      this.untreatedArr.push(item);
    } else if (item.status === 2) {
      this.doingArr.push(item);
    } else { this.recoveryArr.push(item) }
  }

  sortTimeArr(arr) {
    arr.forEach((c) => {
      c.time = this.getTime(c.alarmTime)
    })
    return arr.sort((a, b) => {
      return b.time - a.time
    })
  }

  getTime(time) {
    let timer;
    timer = time.substring(0, 19);
    timer = timer.replace(/-/g, '/');
    return new Date(timer).getTime();
  }

  chartItemClick(status) {
    const sortUntreated = this.sortTimeArr(this.untreatedArr),
      sortDoing = this.sortTimeArr(this.doingArr),
      sortRecovery = this.sortTimeArr(this.recoveryArr);
    switch (status) {
      case 0:
        this.listData = [...sortUntreated, ...sortDoing, ...sortRecovery];
        break;
      case 1:
        this.listData = sortUntreated;
        break;
      case 2:
        this.listData = sortDoing;
        break;
      case 3:
        this.listData = sortRecovery;
        break;

    }
  }

  // tab页切换
  changeAlarmTab(type) {
    console.log(type);
    this.state = type ? 1 : 0;
    this.load = this.loadingService.load(null);
    this.getList(this.state);
  }

  // 点击告警数据弹框（处理或查看）
  async showPopup(data) {
    console.log(data, ':点击告警数据弹框');
    // 已处理的不能点击
    let queryParams: any;
    if (data.status === 1) {
      const modal = await this.modalCtrl.create({
        component: PromptAlarmModal,
        componentProps: {
          'title': '告警处理',
        }
      });
      await modal.present();
      const res = await modal.onDidDismiss();
      if (res.data === 0 || res.data === 1) {// 点击按钮跳转
        queryParams = {
          isLook: res.data ? false : true, // 是否查看
          data: data, // 当前数据
          type: true, // iot告警进入状态
          alarmType: this.state === 1 ? data.alarmType : data.alarmType === 1 ? data.alarmType : 2 + data.alarmType, // 告警类别
          title: '物联告警详情',
          url: 'tabs/home/AlarmDetailPage/AlarmSolveComponent', // 子级处理描述跳转url
          callback: () => {// 返回回调，更新列表状态
            this.promptCallback();
          }
        }
        this.goToAlarmDetail(queryParams)
      }
    } else {
      queryParams = {
        isLook: this.createUserId === data.lastUserId ? data.status === 3 ? true : false : true, // 是否查看
        data: data, // 当前数据
        type: true, // iot告警进入状态
        alarmType: this.state === 1 ? data.alarmType : data.alarmType === 1 ? data.alarmType : 2 + data.alarmType, // 告警类别
        title: '物联告警详情',
        url: 'tabs/home/AlarmDetailPage/AlarmSolveComponent', // 子级处理描述跳转url
        callback: () => {// 返回回调，更新列表状态
          this.promptCallback();
        }
      };
      this.goToAlarmDetail(queryParams)
    }
  }

  promptCallback() {
    this.getList(this.state);
  }

  goToAlarmDetail(queryParams) {
    this.navCtrl.navigateForward(['tabs/home/AlarmDetailPage'], {
      queryParams: queryParams
    })

  }

  // 下拉刷新
  doRefresh(refresher) {
    this.getList(this.state);
    setTimeout(() => {
      console.log('Async operation has ended');
      if (refresher) {
        refresher.complete();
      }
    }, 500);
  }

  goBack() {
    this.navCtrl.pop();
  }
}
